/*
Returns a list of results from Google for the given query.
            - type : SEARCH,
            - start: maximum 100 results => start 1-10 with count=10,
            - count: maximum 10,
There is a daily limit of 10,000 queries. Google Custom Search is a paid service.
        
 */
package ACH.mod.Snippet;

/**
 *
 * @author adriancruz11c
 */

import ACH.app.util.ReadingDataDB;
import ACH.app.util.ReadingDataDB.ObjData;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Search {
//protected final static String KeyG = "TuKey:porEjemplo:AIzaSyBxe9jC4WLr-Rry_5OUMOZ7PCsEyWpiU48";
 
/*protected final static String KeyG = "AIzaSyBxe9jC4WLr-Rry_5OUMOZ7PCsEyWpiU48"; //esta es una KEY publica (la comparten varios usuarios) lo mejor es que coloquen su KEY para las 100 consultas gratuitas esclusivas para ustedes o más consultas dando datos de su tarjeta bancaria al formulario de Google dónde dan de alta su KEY
//protected final static String KeyG = "AIzaSyC1VbYl2lUCofzaM0QnWR7hu96DoVsZmdk";
protected final static String cxG = "775331337241.apps.googleusercontent.com"; //crea tu propio cx y colocalo aquí xfa (atte: Adrián)
//otro ejemplo de cx es 000579440470800426354:_4qo2s0ijsi   (GOOGLE_CUSTOM_SEARCH_ENGINE)
protected final static int CountG = 10;
//protected final static int MaxQuerysG = 2; //las primeras 100 son gratuitas 
//MaxQuerysG es por consulta, solo aplica por día, utilizar las primeras 100 gratuitas
private static final String GOOGLE_SEARCH ="https://www.googleapis.com/customsearch/v1?";*/
    

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) { sb.append((char) cp);}
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
      System.out.println(url);
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {        
      is.close(); // is.reset();
    }
  }
  public static JSONObject getJsonWordRF(String url, String q) throws UnsupportedEncodingException, IOException, JSONException{
      q = URLEncoder.encode(q, "UTF-8");   
      return readJsonFromUrl(url+q);
      
  }
    public static JSONObject readJsonFromQ(String q, String exact, int start, ReadingDataDB.ObjData dat) throws IOException, JSONException {
    q = URLEncoder.encode(q, "UTF-8");   
    exact = URLEncoder.encode(exact, "UTF-8");   
    String url=""+dat.getSEGoogleSearchURL() +"start="+start+"&num="+dat.getSEGoogleCount()+"&key="+dat.getSEGoogleKey()+
            "&cx="+dat.getSEGoogleClientID()+"&q="+q+"&exactTerms="+exact;
    return readJsonFromUrl(url);
  } 

  public static String[] mainPrint(String q, int maxQ, ReadingDataDB.ObjData dat,JSONObject snipUL) throws IOException, JSONException {     
    q = URLEncoder.encode(q, "UTF-8");
    int MaxQuerysG=maxQ;
    int totQ=Integer.parseInt(dat.getSEGoogleCount());
    String SEurl=""+dat.getSEGoogleSearchURL() +"&num="+dat.getSEGoogleCount()+"&key="+dat.getSEGoogleKey()+"&cx="+dat.getSEGoogleClientID();
    String snippets[]=new String[MaxQuerysG*totQ];
    try  {
        JSONObject json = snipUL;//readJsonFromUrl(""+SEurl+"start=1&q="+q+"");
        JSONObject nx;                                                                                                                                              
        json=(JSONObject) json.get("queries");    
        JSONArray jsNext;    
        for (int i=1; i<MaxQuerysG*totQ;i=nx.getInt("startIndex")){    
            json=Cicl(""+SEurl+"start="+i+"&q=&exactTerms="+q+"", snippets, i, snipUL);       
            if(json==null)
                break;           
            jsNext=(JSONArray) json.get("nextPage");                 
            nx= (JSONObject) jsNext.get(0);              
    }    
    return snippets;
    }catch(Exception ex) {
    return snippets;
    }    
  }
  
  public static  JSONObject Cicl(String url, String[] elems, int n, JSONObject snipUL) throws IOException{
    JSONObject json,json2;    
        try {
            if (n==1)
                json = snipUL;
            else
                json = readJsonFromUrl(url);  
            JSONObject jsG=json;           
            json2=json;
            JSONArray jsonA=(JSONArray) jsG.get("items");   
            String snippet[]=new String[jsonA.length()];
            for (int i=0; i< jsonA.length();i++){
                json=(JSONObject) jsonA.get(i);
                snippet[i]=(String) json.get("snippet");                
                elems[n-1+i]=snippet[i];
                //System.out.println(snippet[i]+"\n");
            }
           json=(JSONObject) json2.get("queries");
           return json;
         } catch (JSONException ex) {
            Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
            return null;
         }
  }
  public long numResultsFromWeb_exact(String q, String exact,ReadingDataDB.ObjData dat) throws UnsupportedEncodingException, IOException, JSONException {                        
        return this.totalResults(readJsonFromQ(q, exact, 1,dat));
      }
      
    public long numResultsFromWeb(String q,ReadingDataDB.ObjData dat) throws UnsupportedEncodingException, IOException, JSONException {    
           return this.totalResults(readJsonFromQ(q, "", 1, dat));
    }         
    public long totalResults(JSONObject json){
        System.out.println("Results-request::"+ json);
        JSONObject  nx;
        JSONArray jsNext;
        long i=-1;
         try {    
           json=(JSONObject) json.get("queries");
           jsNext=(JSONArray) json.get("request");            
           nx= (JSONObject) jsNext.get(0);            
           i=Long.parseLong(nx.getString("totalResults"));                   
         } catch (JSONException ex) {   
             return -1;
         }         
        return i;
    }     
}